package com.liyuncong.algorithm.algorithm_similarity.impl;

import com.liyuncong.algorithm.algorithm_similarity.entity.Vector;
import com.liyuncong.algorithm.algorithm_similarity.similarity.ComputeSimilarity;
import com.liyuncong.algorithm.algorithm_similarity.util.VectorUtil;

/**
 * 通过余弦定理计算两个向量的相似性
 * @author yuncong
 *
 */
public class Cosine implements ComputeSimilarity {

	public float compute(Vector vector1, Vector vector2) {
		float dotProduc = VectorUtil.dotProduct(vector1, vector2);
		float vector1Size = VectorUtil.computeVectorSize(vector1);
		float vector2Size = VectorUtil.computeVectorSize(vector2);
		float consine = dotProduc / (vector1Size * vector2Size);
		// 纠正由于开方造成的误差
		if (consine > 1) {
			consine = 1;
		}
		return consine;
	}

}
